﻿package fpc.styles;
import flash.Lib;
import fpc.layouts.ILayoutable;
import fpc.styles.skins.SkinType;
import fpc.styles.skins.TextFormatType;
import fpc.utils.IFactory;
import flash.utils.TypedDictionary;

class Style
{
	public static var defaultStyle(getDefaultStyle, setDefaultStyle):Style;
	static var _defaultStyle:Style;
	static function getDefaultStyle()
	{
		if (_defaultStyle == null)
		{
			_defaultStyle = new Style();
		}
		return _defaultStyle;
	}
	static function setDefaultStyle(value)
	{
		return _defaultStyle = value;
	}
	
	var _dictionary:TypedDictionary<Dynamic, Dynamic>;
	
	public function new()
	{
		_dictionary = new TypedDictionary<Dynamic, Dynamic>();
	}
	
	public function getSkin<T>(skinType:SkinType<T>):IFactory<T>
	{
		return _dictionary.get(skinType);
	}
	
	public function setSkin<T>(skinType:SkinType<T>, skin:IFactory<T>):Style
	{
		_dictionary.set(skinType, skin);
		return this;
	}
	
	public static function findSkin<T>(component:ILayoutable, type:SkinType<T>):IFactory<T>
	{
		return findValue(component, type, type.defaultSkin);
	}
	
	public function getTextFormat(type:TextFormatType):ExtendedTextFormat
	{
		return _dictionary.get(type);
	}
	
	public function setTextFormat(type:TextFormatType, value:ExtendedTextFormat):Style
	{
		_dictionary.set(type, value);
		return this;
	}
	
	public static function findTextFormat(component:ILayoutable, type:TextFormatType):ExtendedTextFormat
	{
		return findValue(component, type, type.defaultTextFormat);
	}
	
	static function findValue(component:ILayoutable, type:Dynamic, defaultValue:Dynamic):Dynamic
	{
		var current:ILayoutable = component;
		while (current != null)
		{
			var styleOwner:IStylized = Lib.as(current, IStylized);
			if (styleOwner != null)
			{
				var style = styleOwner.style;
				if (style != null)
				{
					var skin = style._dictionary.get(type);
					if (skin != null)
					{
						return skin;
					}
				}
			}
			current = current.parent;
		}
		
		var style = _defaultStyle;
		if (style != null)
		{
			var skin = style._dictionary.get(type);
			if (skin != null)
			{
				return skin;
			}
		}
		
		return defaultValue;
	}
}